import Axios from 'axios'

const request = Axios.create({
  headers: { 'Content-Type': 'application/json' },
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: 5000
})

request.interceptors.request.use((config) => {
  const token = localStorage.getItem('token')

  if (token) config.headers.Authorization = `Bearer ${token}`

  return config
})

request.interceptors.response.use(
  (response) => {
    if (response.status === 401) {
      localStorage.removeItem('token')
      window.location.href = 'user/login'
    }
    return response
  },
  (error) => {
    console.log('Axios Error:', error)
    return error.response
  }
)

export const ApiGet = async (url: string, params = {}, configs = {}) => {
  return await request.get(url, { params, ...configs })
}

export const ApiPost = async (url: string, data = {}, configs = {}) => {
  return await request.post(url, data, configs)
}

export const ApiPut = async (url: string, data = {}, configs = {}) => {
  return await request.put(url, data, configs)
}

export const ApiDelete = async (url: string, data = {}, configs = {}) => {
  return await request.delete(url, { data, ...configs })
}

export const ApiPatch = async (url: string, data = {}, configs = {}) => {
  return await request.patch(url, data, configs)
}
